package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.es.service.EsService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;


@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {

    public static final String APP_INFO_ARTICLE = "app_info_article";
    /**
     * 注入es操作的service
     */
    @Autowired
    private EsService esService;

    /**
     * 注入静态页面的地址
     */
    @Value("${file.minio.readPath}")
    private String readPath;


    @Autowired
    private ApUserSearchService apUserSearchService;





    /**
     *  实现搜索功能
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDTO dto) {
        //检查参数
        if (dto == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"数据不能为空");
        }

        ApUser user = AppThreadLocalUtils.getUser();
        if(user !=null) dto.setEntryId(user.getId());
        // 异步调用保存用户输入关键词记录
        apUserSearchService.insert( dto);

        //构建条件查询对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //创建多重条件查询对象
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        //关键词搜索      算分查询             分词查询           查的字段        查询的内容
        boolQueryBuilder.must(QueryBuilders.matchQuery("title",dto.getSearchWords()));

        //查询小于最小的时间的数据
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime().getTime()));

        //分页
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(dto.getPageSize());

        //按照发布时间倒序
        searchSourceBuilder.sort("publishTime", SortOrder.DESC);

        //高亮三要素
        //创建一个高亮对象
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");    //需要高亮的字段
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");    //前缀
        highlightBuilder.postTags("</font>");   //后缀

        searchSourceBuilder.highlighter(highlightBuilder);

        //将多重条件传到查询对象中
        searchSourceBuilder.query(boolQueryBuilder);

        //查询
        PageResponseResult result = esService.search(searchSourceBuilder, SearchArticleVO.class, APP_INFO_ARTICLE);

        //获取结果
        List<SearchArticleVO> list = (List<SearchArticleVO>) result.getData();
        //判断结果
        if (!CollectionUtils.isEmpty(list)){
            for (SearchArticleVO searchArticleVO : list) {
                searchArticleVO.setStaticUrl(readPath + searchArticleVO.getStaticUrl());
            }
        }

        return result;
    }


    /**
     * 添加索引文章 (文章上架和发布)
     * @param article
     */
    @Override
    public void saveArticle(SearchArticleVO article) {
        esService.save(article,APP_INFO_ARTICLE);
    }


    /**
     * 删除索引文章 (文章下架和删除)
     * @param articleId
     */
    @Override
    public void deleteArticle(String articleId) {
        esService.deleteById(APP_INFO_ARTICLE,articleId);
    }


}
